//
//  WBNetworkManager.swift
//  
//
//  Created by zj on 2017/10/15.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {
    
    /// 静态区／常量／闭包／在第一次访问时，执行闭包
    static let shared: WBNetworkManager = {
       
        let instance = WBNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->()) {
        
        guard let token = userAccount.access_token else {
            
            // 发送通知，提示用户登录
            print("没有 token ！需要登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            completion(nil, false)
            
            return
        }
        
        var parameters = parameters
        
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token as AnyObject
        
        request(URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    /// 使用一个方法
    /// 封装 AFN 的GET／POST 请求
    ///
    /// - Parameters:
    ///   - method: GET ／ POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject], completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->()) {
        
        /// 成功回调
        let success = {(task: URLSessionDataTask, json: Any?)->() in
            completion(json as AnyObject, true)
        }
        
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            // 针对 403
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                
                // 发送通知，提示用户登录
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
            }
            
            print("网络请求错误: \(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
